<?php
namespace app\common\controller;

use app\admin\model\Apply;
use app\common\library\Token;
use app\admin\model\Admin;
use app\common\model\User;

class AdminApi extends Api
{
    /**
     * 当前管理员模型
     * @var Admin
     */
    protected $admin = null;

    protected $adminToken = '';

    protected function _initialize()
    {
        // 禁用原有的用户认证
        $this->noNeedLogin = ['*'];
        $this->noNeedRight = ['*'];

        parent::_initialize();

        // 执行管理员认证
        $this->authenticateAdmin();
    }

    /**
     * 管理员认证逻辑
     */
    protected function authenticateAdmin()
    {
        // 获取管理员token (使用token参数)
        $token = $this->request->server('HTTP_TOKEN',
            $this->request->request('token'));

        if (!$token) {
            return;
        }

        // 使用新的缓存键格式
        $cacheKey = 'admin_token_' . $token;

        // 从缓存获取管理员ID
        $adminId = cache($cacheKey);
        if (!$adminId) {
            return;
        }

        // 获取管理员信息
        $admin = Admin::get($adminId);
        if (!$admin || $admin['status'] !== 'normal') {
            return;
        }

        // 认证成功
        $this->admin = $admin;
        $this->adminToken = $token;
        $this->_logined = true; // 标记为已登录
    }

    /**
     * 检查管理员是否登录
     */
    protected function requireAdminLogin()
    {
        if (!$this->admin) {
            $this->error('请先登录管理员账号', null, 401);
        }
    }

    /**
     * 管理员登录方法
     */
    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');

        if (!$username || !$password) {
            $this->error('用户名和密码不能为空');
        }

        $admin = Admin::get(['username' => $username]);

        if (!$admin) {
            $this->error('管理员账号不存在');
        }

        if ($admin->password != $this->getEncryptPassword($password, $admin->salt)) {
            $admin->save(['loginfailure' => $admin->loginfailure + 1]);
            $this->error('密码错误');
        }

        // 生成token
        $token = $this->generateAdminToken($admin->id);

        $this->success('登录成功', [
            'admin_token' => $token,
            'admin_info' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'avatar' => $this->request->domain().$admin->avatar,
                'email' => $admin->email,
                'mobile' => $admin->mobile,
                'userid'=>$admin->userid
            ],
            'userinfo' => User::get($admin->userid)
        ]);
    }

    /**
     * 生成管理员token
     */
    private function generateAdminToken($adminId)
    {
        $token = \fast\Random::uuid();
        $expire = 7200; // 2小时有效期

        // 存储到缓存 (使用新的缓存键格式)
        cache('admin_token_' . $token, $adminId, $expire);

        return $token;
    }

    /**
     * 管理员登出
     */
    public function logout()
    {
        if ($this->adminToken) {
            // 删除token缓存
            cache('admin_token_' . $this->adminToken, null);
        }
        $this->success('登出成功');
    }

    /**
     * 获取管理员信息
     */
    public function profile()
    {
        $this->requireAdminLogin();

        $admin = $this->admin;
        $this->success('获取成功', [
            'admin_info' => [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'avatar' => $this->request->domain().$admin->avatar,
                'email' => $admin->email,
                'mobile' => $admin->mobile,
                'userid'=>$admin->userid
            ],
            'userinfo' => User::get($admin->userid),
            'storeInfo' => Apply::where(['userid'=>$admin->userid])->field('name,idcard,mobile,sname')->find()
        ]);
    }
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
}